<template>
  <div  v-loading="loading"
        element-loading-text="订单提交中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)">
    <el-dialog class="add_address_wrap" title="新增收货信息" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" label-position='left'  ref="ruleForm"  :rules="rules">
        <el-form-item class="form_item" label="姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item class="form_item" label="手机" prop="tel">
          <el-input v-model="ruleForm.tel"></el-input>
        </el-form-item>
        <el-form-item class="form_item" label="地址" prop="address">
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange">
          </el-cascader>
          <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item class="form_item">
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <h2>填写并核对订单信息</h2>
    <section class="sure_orde">
      <section class="shipping_method">
        <h3>
          <span>收货人信息</span>
          <span class="add_newadd" @click="open">新增收货地址</span>
        </h3>
        <div v-if="address.id&&!allAdd.isShow" class="default">
          <span class="select">{{address.shipto}}<i></i></span>
          <span>{{address.shipto}}</span>
          <span>{{address.province}} {{address.city}} {{address.region}} {{address.address}}</span>
          <span>{{address.phone}}</span>
          <span v-if="address.id ==defAdd.id" class="def">默认地址</span>
          <span v-else class="add_newadd" @click="setDefault(address.id)">设为默认</span>
        </div>
        <div class="more_add">
          <span @click="loadMoreAdd(0)">选择其他地址</span>
        </div>
        <div v-if="allAdd.isShow" class="default" v-for="item in allAdd.allAddress" :key="item.id">
          <span @click="changeSelect('isChoose',item.id,item)" :class="{select:isSelect.isChoose == item.id}" class="no_select">{{item.shipto}}<i></i></span>
          <span>{{item.shipto}}</span>
          <span>{{item.province}} {{item.city}} {{item.region}} {{item.address}}</span>
          <span>{{item.phone}}</span>
          <span>
            <span v-if="item.id == defAdd.id" class="def">默认地址</span>
            <span v-else class="add_newadd" @click="setDefault(item.id)">设为默认</span>
            <span class="add_newadd" style="color:red;" @click="deleteAddr(item.id)">删除</span>
          </span>
        </div>
        <div v-if="allAdd.isShow&&!allAdd.allAddress.length" style="text-align:center;">
          暂无更多地址
        </div>
        <div v-if="allAdd.isShow &&allAdd.allAddress.length" style="text-align:center;">
          <el-pagination
            @current-change = 'changeCurrent'
            layout="prev, pager, next"
            :page-count="pageCount">
          </el-pagination>
        </div>
      </section>
      <section class="shipping_method" v-if="sureOrder.getway">
        <h3>配送方式</h3>
        <div class="shop_method_btn">
          <span @click="changeSelect('shopMethod','线上快递')" :class="{select:isSelect.shopMethod==='线上快递'}">线上快递<i></i></span>
          <span @click="changeSelect('shopMethod','线下教练处领取')" :class="{select:isSelect.shopMethod ==='线下教练处领取'}">线下教练处领取<i></i></span>
        </div>
      </section>
      <!-- <section class="shipping_method">
        <h3>发票信息</h3>
        <div class="shop_method_btn">
          <span @click="changeSelect('invoice','电子发票')" :class="{select:isSelect.invoice ==='电子发票'}">电子发票<i></i></span>
          <span @click="changeSelect('invoice','普通发票')" :class="{select:isSelect.invoice ==='普通发票'}">普通发票<i></i></span>
        </div>
      </section> -->
      <!-- <section class="shipping_method">
        <h3>使用积分</h3>
        <div class="shop_method_btn">
          <span @click="changeSelect('integral','不使用')" :class="{select:isSelect.integral ==='不使用'}">不使用<i></i></span>
          <span @click="changeSelect('integral','使用')" :class="{select:isSelect.integral ==='使用'}">使用<i></i></span>
        </div>
      </section> -->
      <section class="shipping_method">
        <h3>确认订单信息</h3>
        <header class="sure_ordershow_head">
          <span class="sure_order_img">购买商品</span>
          <span class="sure_order_info">商品属性</span>
          <span class="sure_order_price">单价</span>
          <span class="sure_order_num">数量</span>
          <!-- <span class="sure_order_discount">优惠方式</span> -->
          <span class="sure_order_distribution">配送方式</span>
        </header>
        <section class="sure_ordershow_content" v-for="item in sureOrder.data" :key="item.id">
          <span class="sure_order_img">
            <img :src="item.image" alt="">
          </span>
          <span class="sure_order_info">
            <span class="name">{{item.course||item.specialty}}</span>
            <span>{{item.size}} {{item.sex}}{{item.system}} {{item.date}}</span>
            <span>{{item.star}}{{item.star?'星级':''}}{{item.color}}</span>
          </span>
          <span class="sure_order_price">{{item.price}}</span>
          <span class="sure_order_num">{{item.quantity}}</span>
          <!-- <span class="sure_order_discount">{{isSelect.integral}}积分</span> -->
          <span class="sure_order_distribution">{{isSelect.shopMethod}}</span>
        </section>
      </section>
      <div class="sure_order">
        <!-- <div>运费 <span class="price"> {{0}}</span></div> -->
        <div>总价<span class="price">￥{{sureOrder.total||0}}</span></div>
        <span class="sure_order_btn" @click="sureOrderBuy">付款</span>
      </div>
    </section>
    <el-dialog  class="pay_img"  title="请用微信扫描下方二维码支付"
                :before-close="handleClose"
                :visible.sync="dialogFormVisible1">
      <img :src="payImg" alt="">
      <div>二维码有效期两小时，请在有效期内完成付款</div>
    </el-dialog>
  </div>
</template>
<script>
import { regionData,CodeToText}  from 'element-china-area-data'
export default {
  data() {
    //提交收货地址数据判断
    var checkName = (rule,value,callback)=>{
      if (!value.trim()) {
        callback(new Error('请输入姓名')); 
      }
      callback()
    };
    var checkAddress = (rule,value,callback)=>{
        if(!this.fullAddress ||!value.trim()){
          callback(new Error('请输入地址')); 
        }
        callback()
    };
    var checkTel = (rule,value,callback)=>{
      let reg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      if (!reg.test(value)) {
        //验证没通过
        this.isTel = false;
        callback(new Error('请输入正确的手机号'));
      }
      this.isTel = true;
      callback()
    };
    return {
      pageCount:1,
      sureOrder:{},
      isSelect:{
        isChoose:'',//已选择收货地址id
        shopMethod:'线上快递',//默认选择数据
        invoice:'电子发票',
        integral:'不使用',
      },
      defAdd:{},//默认地址
      address:{},//展示在已选地址
      allAdd:{//用户所有地址
        isShow:false,
        allAddress:[]
      },
      dialogFormVisible: false,//新增收货地址弹框
      dialogFormVisible1:false,//付款二维码框
      payImg:'',//付款二维码
      fullAddress:[],//三级联动地址
      rules:{
        name: [
          { validator: checkName, trigger: 'blur'  },
        ],
        tel: [
          { validator: checkTel, trigger: 'blur'  },
        ],
        address:[
          { validator: checkAddress, trigger: 'blur'  }
        ]
      },
      ruleForm:{
        name: '',
        tel:'',
        address:'',
      },
      options: regionData,
      selectedOptions: [],
      formLabelWidth: '120px',
      loading:false,
      resGo:true
    };
  },
  mounted(){
    this.getDefAddress();
    this.GLOBAL.tokenRequest({
      method:'post',
      baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
      url:'orders/check',//展示确认订单列表
      data:{
        id:this.$route.params.id
      }
    }).then(({data:data})=>{
      if (data =='购物车不存在') {
        this.$router.push('/car')
      }
      this.sureOrder = data;
    })
  },
  methods: {
    deleteAddr(id){
      this.GLOBAL.tokenRequest({
        method:'post',
        baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
        url:'shiptos/destroy',
        data:{
          id
        }
      }).then(({data:data})=>{
        if (data) {
          this.$message({
            type:'success',
            message:'删除地址成功'
          })
          this.loadMoreAdd(0)
        }else{
          this.$message({
            type:'error',
            message:'删除地址失败'
          })
        }
      })
    },
    changeCurrent(val){
      this.loadMoreAdd(val-1)
    },
    open(){
      this.dialogFormVisible = true;
    },
    getDefAddress(){
      this.GLOBAL.tokenRequest({
        baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
        url:'shiptos/default',//获取默认地址
      }).then(({data:data})=>{
        if (!data[0]) {
          return
        }
        this.isSelect.isChoose = data[0].id;
        this.address = data[0];
        this.defAdd = data[0];
      })
      
    },
    setDefault(id){
      this.GLOBAL.tokenRequest({
        method:'post',
        baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
        url:'shiptos/set',//设置默认地址
        data:{
          id
        }
      }).then(({data:data})=>{
        if(data)this.getDefAddress();
        this.allAdd.isShow = false;
      })  
    },
    changeSelect(key,val,item){
      this.isSelect[key] = val;
      if(key=='isChoose'){//更改展示地址
        this.address = item;
        this.allAdd.isShow = false;
      }
    },
    loadMoreAdd(page){
      this.GLOBAL.tokenRequest({
        baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
        url:'shiptos/show',//获取所有地址
        param:{
          page,
        }
      }).then(({data:data})=>{
        this.allAdd.allAddress = data.data;
        this.allAdd.isShow = true;
        this.pageCount = data.pagination.page_count;
      })
    },
    sureOrderBuy(){//生成订单并结账
      this.loading = true;
      if (!this.isSelect.isChoose||!this.$route.params.id) {
        return;
      }
      this.GLOBAL.tokenRequest({
        method:'post',
        baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
        url:'orders/cadd',//生成订单
        data:{
          key:JSON.stringify({
                data:this.sureOrder.data,
                id:this.$route.params.id,
                getway:this.isSelect.shopMethod,
                address:this.isSelect.isChoose,
              })}
      }).then(({data:data})=>{
        if(data){//如果订单号存在
          let olderID = data; 
          this.loading = false;
          this.GLOBAL.tokenRequest({
            method:'post',
            baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
            url:'pays/wx',//获取二维码
            data:{
              orderid:data//订单号
            }
          }).then(({data:data})=>{
            this.payImg = data;
            this.dialogFormVisible1 = true;
            this.monitorPay(olderID)//做处理 进行页面跳转进行页面跳转
          })
        }else{//订单号不存在
          this.$message.error('订单生成失败')
          this.loading = false;
        }
      })  
    },
    monitorPay(orderid){//建立轮询返回true付款成功
      this.GLOBAL.request({
        method:'post',
        baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
        url:'pays/res',
        data:{
          orderid
        }
      }).then(({data:data})=>{
        if (!data.status&&this.resGo) {//没付款
          this.monitorPay(orderid)
        }
        if (data.status==1) {//成功
          this.dialogFormVisible1 = false;
          this.$message({
            type:'success',
            message:data.message
          })
          setTimeout(()=>this.router.push('/listAction'),500)
        }
        if (data.status==2) {//超时
          this.dialogFormVisible1 = false;
          this.$message({
            type:'error',
            message:data.message
          })
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认取消支付？')
        .then(_ => {
          done();
          this.resGo = false;
          this.$router.push({path:'/listAction'})
        })
        .catch(_ => {});
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.GLOBAL.tokenRequest({
            method:"post",
            baseURL:this.GLOBAL.RNTY_SHOP_MALL_URL,
            url:"shiptos/add",//新增收货地址
            data: {
              shipto:this.ruleForm.name,
              phone:this.ruleForm.tel, 
              province:this.fullAddress[0], 
              city:this.fullAddress[1] ,
              region:this.fullAddress[2],
              address:this.ruleForm.address,
            }
          }).then(({data:data})=>{
            this.dialogFormVisible = data? false:true;
            this.loadMoreAdd(0);
            this.allAdd.isShow = true;
          })
            // this.$router.push({path:'/listAction'})
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange (value) {
      this.fullAddress = [];
      this.fullAddress.push(CodeToText[value[0]],CodeToText[value[1]],CodeToText[value[2]])
    }
  } 
}
</script>
<style scoped>
.sure_orde{
  width:1200px;
  padding:24px;
  box-sizing: border-box;
  border:1px solid #ccc;
  border-bottom:none;
}
.sure_orde section{
  border-bottom: 1px solid #ccc;
}
.sure_orde .sure_ordershow_content{
  border-bottom:0;
}
h2{
  font-size: 16px;
  color:#666;
  line-height: 82px;
}
h3{
  display: flex;
  justify-content: space-between;
  font:18px/22px "微软雅黑";
  font-weight: bold;
  color:#666666;
  margin: 32px 0 23px 0;
}
.shop_method_btn,.default{
  display: flex;
  padding-left:39px;
  margin-bottom: 27px;
}
.default{
  margin-bottom:15px;
  justify-content: space-between;
}
.shop_method_btn span,.default .select,.default .no_select{
  font:14px/19px "宋体";
  border:2px solid #ccc;
  padding: 0 14px;
  min-width: 82px;
  color:#666;
  text-align: center;
  box-sizing: border-box;
  margin-right: 14px;
  cursor: pointer;
}
.select{
  border-color:#0076c4 !important;
  position: relative;
}
.select i{
  position: absolute;
  right: 0;
  bottom: 0;
  width:14px;
  height:10px;
  background: url('../assets/images/select.png');
}
.def{
  background-color: #dadada;
  color:#f8f8f8;
  line-height: 23px;
  padding:0 5px;
  border-radius: 5px;
}
.more_add{
  padding-left: 39px;
  display: flex;
  margin-bottom: 15px;
}
.more_add span{
  font:14px/16px "微软雅黑";
  cursor: pointer;
}
.add_newadd{
  font-size: 14px;
  font-weight: normal;
  color:#427ab4;
  cursor: pointer;
}
.form_item{
  display: flex;
}
.add_address_wrap .el-dialog{
  width:500px !important;
}
/* 确认订单展示 */
.sure_ordershow_head, .sure_ordershow_content{
  display: flex;
  justify-content: space-around;
  align-items: center;
  font: 14px/24px "微软雅黑";
  margin-bottom: 20px;
  text-align: center;
  padding: 0 38px;
  color:#808080;
}
.sure_order_img{
  width:244px;
}
.sure_order_info{
  width:180px;
}
.sure_order_price{
  width:125px;
}
.sure_order_num{
  width:100px;
}
.sure_order_discount{
  width:130px;
}
.sure_order_distribution{
  width:100px;
}
.sure_order_freight{
  width:140px;
}
.sure_order_tota{
  width:90px;
}
.sure_ordershow_content{
  height:120px;
  background-color: #fff4ef;
}
.sure_order_img img{
  width:130px;
  height:120px;
}
.sure_order_info span{
  display: block;
}
/* 付款按钮 */
.sure_order{
  text-align: right;
}
.sure_order div{
  padding:10px 29px 0 0;
}
.sure_order .price{
  font: 20px/26px "微软雅黑";
  color:#ff6d00;
}
.sure_order .sure_order_btn{
  display: inline-block;
  width:83px;
  height:25px;
  background-color: #ff6d00;
  font:18px/25px "微软雅黑";
  color:#fff;
  text-align: center;
  margin: 12px 29px 0 0 ;
  cursor: pointer;
}
/* 付款 */
.pay_img{
  text-align: center;
}
.pay_img img{
  width:340px;
  height:340px;
}
</style>
